package maintain

import ( "net"
					"fmt"
					"github.com/garyburd/redigo/redis"
					"time"
			 )

type WatchDog struct {
	Id int
	Status string
	Load float32
	Ttl int
	HeartBeat int
	InIp string
	ExIp string
	ReserveServerNumber int
	Servers []*Server
}

type Server struct {
	Id int
	ExAddr string
	InAddr string
	Status string
	Ttl int
	HeartBeat int
	Load float32
	Pid int
	WatchDog *WatchDog
	Rooms []*Room
}

type Room struct {
	Id int
	Type int
	StartAt int
	Server *Server
}

type RoomMap map[int]*Room
type ServerMap map[int]*Server
type WatchDogMap map[int]*WatchDog

type Maps struct {
	RoomMap *RoomMap
	ServerMap *ServerMap
	WatchDogMap *WatchDogMap
}

func (m *Maps) Dump() {
	if m == nil || m.WatchDogMap == nil || m.RoomMap == nil { fmt.Println("Map is nil"); return }
	for key, value := range (*((*m).WatchDogMap)) {
		fmt.Println("wd[", key, "]: status:", value.Status, ", load:", value.Load, ", inip:", value.InIp, 
								", exip:", value.ExIp, ", ttl:", value.Ttl, ", hb:", value.HeartBeat, ", rsrv:", value.ReserveServerNumber)
		for _, srv := range value.Servers {
			fmt.Println("\tserver[", srv.Id, "]: exAddr:", srv.ExAddr, ", inAddr:", srv.InAddr, ", PID: ", srv.Pid,
									", status:", srv.Status, ", load:", srv.Load, ", ttl:", srv.Ttl, ", hb:", srv.HeartBeat)
			for _, room := range srv.Rooms {
				fmt.Println("\t\troom[", room.Id, "]:  type:", room.Type,
					", startAt:", room.StartAt, ", srvId:", room.Server.Id, ", srvLoad:", room.Server.Load)
			}
		}
	}
	for _, room := range (*((*m).RoomMap)) {
		fmt.Println("room[", room.Id, "]:  type:", room.Type,
			", startAt:", room.StartAt)
		if room.Server != nil {
			srv := *room.Server
			fmt.Println("\tserver[", srv.Id, "]: exAddr:", srv.ExAddr, ", inAddr:", srv.InAddr, ", PID: ", srv.Pid,
									", status:", srv.Status, ", load:", srv.Load, ", ttl:", srv.Ttl, ", hb:", srv.HeartBeat)
		}
	}
}

type RedisData struct {
	ServerAddress *net.TCPAddr
	LocalIp string
	TcpConn *net.TCPConn
	Conn *redis.Conn
	TimeDiff int64
}

func (data *RedisData) Copy (other *RedisData) {
	data.ServerAddress = other.ServerAddress
	data.LocalIp = other.LocalIp
	data.TcpConn = other.TcpConn
	data.Conn = other.Conn
	data.TimeDiff = other.TimeDiff
}

const (
	WatchDogStatusOffline = "offline"
	WatchDogStatusReady   = "ready"
	WatchDogStatusClose   = "close"
)
const (
	ServerStatusReserve = "reserve"
	ServerStatusRunning = "running"
	ServerStatusClose   = "close"
)
const (
	RoomTypeUnknown  = "unknown"
	RoomTypeNormal   = "normal"
	RoomTypeHuge     = "huge"
)

func (redisData *RedisData) Now () int64 {
	now := time.Now().Unix()
	return now + redisData.TimeDiff
}